const sequelize = require('../config/database');
const { validationResult } = require('express-validator');
const { Like, Video } = require('../models');
const { NotFoundError } = require('../utils/errors');

class LikeController {
  // 视频点赞/取消点赞
  static async toggleVideoLike(req, res) {
    try {
      const videoId = req.params.videoId;
      const userId = req.user.id;
      
      // 检查视频是否存在
      const video = await Video.findByPk(videoId);
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      // 切换点赞状态
      const result = await Like.toggleLike(userId, videoId);
      
      // 如果是点赞操作，且点赞者不是视频作者，创建点赞消息通知
      if (result.liked && userId !== video.user_id) {
        try {
          // 异步创建消息，不影响主流程
          await Message.createLikeMessage(userId, video.user_id, videoId, 'video');
        } catch (messageError) {
          console.error('创建点赞消息失败:', messageError);
          // 消息创建失败不影响点赞操作
        }
      }
      
      res.json({ 
        success: true, 
        message: result.liked ? '点赞成功' : '取消点赞成功',
        data: {
          liked: result.liked,
          likeCount: result.likeCount
        }
      });
    } catch (error) {
      console.error('操作视频点赞失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  

  // 检查用户是否点赞了视频
  static async checkVideoLiked(req, res) {
    try {
      const videoId = req.params.videoId;
      const userId = req.user.id;
      
      // 检查视频是否存在
      const video = await Video.findByPk(videoId);
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      const liked = await Like.isLiked(userId, videoId);
      const likeCount = await Like.count({ where: { videoId } });
      
      res.json({ 
        success: true, 
        data: {
          liked,
          likeCount
        }
      });
    } catch (error) {
      console.error('检查视频点赞状态失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 批量检查视频点赞状态
  static async batchCheckVideoLiked(req, res) {
    try {
      const { videoIds } = req.body;
      const userId = req.user.id;
      
      if (!Array.isArray(videoIds)) {
        return res.status(400).json({ success: false, message: 'videoIds必须是数组' });
      }
      
      const results = await Like.batchCheckLiked(userId, videoIds);
      
      res.json({ 
        success: true, 
        data: results
      });
    } catch (error) {
      console.error('批量检查视频点赞状态失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  // 获取视频的点赞列表（需要管理员权限）
  static async getVideoLikes(req, res) {
    try {
      const { page = 1, limit = 50 } = req.query;
      const videoId = req.params.videoId;
      
      // 检查视频是否存在
      const video = await Video.findByPk(videoId);
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在' });
      }
      
      const { count, rows } = await Like.findAndCountAll({
        where: { videoId },
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit),
        order: [['createdAt', 'desc']],
        include: [{
          model: Like.User,
          attributes: ['id', 'username', 'avatar']
        }]
      });
      
      res.json({
        success: true,
        data: {
          likes: rows,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取视频点赞列表失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }
}

module.exports = LikeController;